<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
      <el-form-item label="学生姓名" prop="className">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入考学生姓名"
          clearable
          size="small"
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学生手机号" prop="status">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入考学生姓名"
          clearable
          size="small"
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="bclassList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column
        label="学生姓名"
        align="center"
        prop="name"
        width="180"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column
        label="学生学号"
        align="center"
        prop="studentId"
        width="180"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column label="班级" align="center" prop="className" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="手机号" align="center" prop="phone" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column
        label="作业/试卷试卷总分"
        align="center"
        prop="totalPoints"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column
        label="作业/试卷得分"
        align="center"
        prop="examScore"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column label="是否提交" align="center" prop="isSubmit" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.isSubmit==0">未提交</el-tag>
          <el-tag type="success" v-if="scope.row.isSubmit==1">已提交</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否批改" align="center" prop="isSubmit" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.correctStatus==0">未批改</el-tag>
          <el-tag type="success" v-if="scope.row.correctStatus==1">已批改</el-tag>
          <el-tag type="success" v-if="scope.row.correctStatus==2">自动批改</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="提交时间" align="center" prop="submitTime" width="160">
        <template slot-scope="scope">{{ parseTime(scope.row.submitTime) }}</template>
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-tooltip
            v-if="scope.row.correctStatus==0"
            class="item"
            effect="dark"
            content="批改"
            placement="top"
          >
            <el-button
              size="mini"
              circle
              type="success"
              icon="el-icon-edit-outline"
              @click="getStudentquery(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="试题查看" placement="top">
            <el-button size="mini" circle icon="el-icon-view" @click="getStudentquery(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!--试卷发布信息填写-->
    <el-dialog title="试题查看" :visible.sync="publishAperVisible" width="900px">
      <template>
        <el-row
          style="text-align: center; padding-bottom: 20px; font-size: 20px; font-weight: bold;"
        >
          <el-col>{{ testpaperList.length>0?testpaperList[0].testpaperName:'' }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>试题列表</span>
                <el-button style="float: right; padding: 3px 0" type="text">&nbsp;</el-button>
              </div>
              <div>
                <el-divider content-position="left">结果标识</el-divider>
                <p>
                  <el-tag type="info" style="margin-right: 5px;margin-bottom: 5px;">未提交</el-tag>
                  <el-tag type="danger" style="margin-right: 5px;margin-bottom: 5px;">错误</el-tag>
                  <el-tag type="success" style="margin-right: 5px;margin-bottom: 5px;">正确</el-tag>
                  <el-tag type="warning" style="margin-right: 5px;margin-bottom: 5px;">未批改</el-tag>
                </p>
                <el-divider content-position="left">答题结果</el-divider>
                <span v-for="item,index in testpaperList" :key="item.id">
                  <el-tag
                    @click="scrollToposition('question-'+index)"
                    v-if="!item.isRight && item.correctStatus!=0"
                    type="info"
                    style="cursor: pointer;margin-right: 5px;margin-bottom: 5px;"
                  >{{ index+1 }}</el-tag>
                  <el-tag
                    @click="scrollToposition('question-'+index)"
                    v-if="item.isRight==0 "
                    type="danger"
                    style="cursor: pointer;margin-right: 5px;margin-bottom: 5px;"
                  >{{ index+1 }}</el-tag>
                  <el-tag
                    @click="scrollToposition('question-'+index)"
                    v-if="item.isRight==1 "
                    type="success"
                    style="cursor: pointer;margin-right: 5px;margin-bottom: 5px;"
                  >{{ index+1 }}</el-tag>
                  <el-tag
                    @click="scrollToposition('question-'+index)"
                    v-if="!item.isRight && item.correctStatus==0 "
                    type="warning"
                    style="cursor: pointer;margin-right: 5px;margin-bottom: 5px;"
                  >{{ index+1 }}</el-tag>
                </span>
              </div>
            </el-card>
          </el-col>
          <el-col :span="18">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>{{ '总分：'+ rowData.totalPoints }}</span>
                <el-button
                  style="float: right; padding: 3px 0"
                  type="text"
                >{{ '得分：'+ (sumCount || 0) }}</el-button>
              </div>
              <div>
                <el-form
                  label-width="80px"
                  v-for="item,index in testpaperList"
                  :key="item.id"
                  :id="'question-'+index"
                >
                  <el-divider content-position="left"></el-divider>
                  <el-form-item :label="'题目'+ (index+1) ">
                    {{item.quesitonName}}
                    <el-tag v-if="item.questionsType==1">单选题</el-tag>
                    <el-tag v-if="item.questionsType==2">多选题</el-tag>
                    <el-tag v-if="item.questionsType==3">判断题</el-tag>
                    <el-tag v-if="item.questionsType==4">填空题</el-tag>
                    <el-tag v-if="item.questionsType==5">问答题</el-tag>
                    <el-tag>{{item.scoresScore || 0}}分</el-tag>
                    <el-tag type="success" v-if="item.isRight==1">正确</el-tag>
                    <el-tag type="danger" v-if="item.isRight==0">错误</el-tag>
                    <label>( {{ item.stuResult }} )</label>
                  </el-form-item>
                  <el-form-item label="选项" v-if="item.questionsType==1 || item.questionsType==2">
                    <div v-for="optItem in JSON.parse(item.options)" :key="optItem.optIdx">
                      <el-tag>{{optItem.optIdx}}</el-tag>
                      <span v-html="optItem.optTxt"></span>
                    </div>
                  </el-form-item>
                  <el-form-item label="得分">
                    <label style="color:#13ce66">{{ item.gradesScores }}</label>
                  </el-form-item>
                  <el-form-item label="正确答案">
                    <label>( {{getUnit(item)}} )</label>
                  </el-form-item>
                  <el-form-item
                    label="批改"
                    v-if="item.correctStatus==0"
                    :rules="[{ required: true, message: '填写批改分数'}]"
                  >
                    <el-input-number
                      v-model="item.gradesScores"
                      :step="0.1"
                      size="mini"
                      :max="Number(item.scoresScore)"
                      label="描述文字"
                    ></el-input-number>
                  </el-form-item>
                </el-form>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="rowData.correctStatus==0" @click="submitCorrect">提交批改</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
  <script>
import { findSchoolClassPageList } from "@/api/classManage/classInfo";
import { findBaseSpaceLocationPageList } from "@/api/baseData/siteManagement";
import { getClassTeacherList } from "@/api/system/user";
import { findBaseSubjectPageList } from "@/api/baseData/profession";
import { subjectList } from "@/api/educational/subject.js";
import {
  queryByStudnet,
  studentquery,
  correctExamByStudent
} from "@/api/studentInfo/examPublish";

export default {
  name: "BClass",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      rowList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      stuCount: 0,
      // 字典表格数据
      bclassList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 班主任
      userOptions: [],
      // 状态数据字典
      statusOptions: [],
      // 班级所属部门
      classDeptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        className: undefined,
        status: undefined,
        classDept: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        classId: [
          { required: true, message: "考试名称不能为空", trigger: "blur" }
        ],
        pubilishType: [
          { required: true, message: "考试开始时间不能为空", trigger: "blur" }
        ]
      },
      subjectList: [],
      majorList: [], //专业
      termTimeList: [],
      courseTypeOptions: [],
      classOptions: [],
      classGradeList: [],
      publishAperVisible: false,
      testpaperList: [],
      rowData: {},
      sumCount: 0,
      id: 0
    };
  },
  created() {
    this.queryParams.id = this.$route.query.id;
    this.id = this.$route.query.id;

    this.getMajortList();
    this.getList();
    this.getClassTeacherList();
    this.getSubjectList();
    this.getClassList();

    this.getDicts("class_grade").then(response => {
      //年级
      this.classGradeList = response.data;
    });
  },
  methods: {
    scrollToposition(key) {
      document.querySelector("#" + key).scrollIntoView();
      console.log(key);
    },
    submitCorrect() {
      //保存批改数据
      let correctDataList = [];
      for (let i = 0; i < this.testpaperList.length; i++) {
        const item = this.testpaperList[i];
        if (item.correctStatus == 0) {
          if (item.gradesScores < 0) {
            this.$message({
              message: "请批改第" + (i + 1) + "题",
              type: "warning"
            });
            return;
          }
          correctDataList.push({
            id: item.id,
            correctStatus: 1,
            gradesScores: item.gradesScores,
            studentId: item.studentId,
            publishId: item.publishId
          });
        }
      }
      correctExamByStudent(correctDataList)
        .then(resp => {
          this.msgSuccess("批改成功");
          this.getList();
          this.publishAperVisible = false;
        })
        .catch(function() {
          this.publishAperVisible = false;
        });

      console.log(correctDataList);
      // correctExamByStudent()
    },
    getUnit(row) {
      let optTxt = "";
      if (row.questionsType == 2) {
        JSON.parse(row.unit).forEach(item => {
          if (item.isRight) {
            optTxt += item.optIdx + "\n";
          }
        });
      } else if (row.questionsType == 4) {
        JSON.parse(row.unit).forEach(item => {
          optTxt += item.optTxt + "\n";
        });
      } else if (row.questionsType == 3) {
        optTxt = row.unit == "yes" ? "对" : "错";
      } else {
        optTxt = row.unit;
      }
      return optTxt;
    },
    getStudentquery(row) {
      //获取学生答题信息
      this.publishAperVisible = true;
      this.rowData = row;
      const _this = this;
      studentquery({ studentId: row.id, publishId: this.$route.query.id }).then(
        resp => {
          this.testpaperList = resp.data;
          this.testpaperList.forEach(item => {
            _this.sumCount += Number(item.gradesScores);
            if (!item.gradesScores) {
              item.gradesScores = undefined;
            }
          });
        }
      );
    },
    handlePublish(row) {
      //打开窗口
      this.form = {
        testPaperId: row.id,
        classId: null,
        pubilishType: null
      };
      this.publishAperVisible = true;
    },
    getClassRoom() {
      findBaseSpaceLocationPageList({
        pageNum: 1,
        pageSize: 1000,
        locationType: 4
      }).then(response => {
        this.classRoomOptions = response.data.list;
      });
    },
    getClassList() {
      //查询班级
      findSchoolClassPageList({
        pageSize: 500,
        pageNum: 1,
        status: 1,
        isGraduation: 0
      }).then(resp => {
        this.classOptions = resp.data.list;
      });
    },
    getTermTimeList() {
      //查询学期
      this.loading = true;
      listTermtime({ pageSize: 100, pageNum: 1, status: 1 }).then(response => {
        this.termTimeList = response.data.list;
      });
    },
    getMajortList() {
      //查询科目
      findBaseSubjectPageList({ pageSize: 100, pageNum: 1, status: 1 }).then(
        response => {
          this.majorList = response.data.list;
        }
      );
    },
    getSubjectList() {
      //查询专柜
      subjectList({ pageSize: 100, pageNum: 1, status: 1 }).then(response => {
        this.subjectList = response.data.list;
      });
    },
    getMajorLable(val) {
      for (let i = 0; i < this.majorList.length; i++) {
        if (this.majorList[i].id == val) {
          return this.majorList[i].subjectName;
        }
      }
    },
    getSubjectLable(val) {
      for (let i = 0; i < this.subjectList.length; i++) {
        if (this.subjectList[i].id == val) {
          return this.subjectList[i].subjName;
        }
      }
    },
    /** 查询班级列表 */
    getList() {
      this.loading = true;
      queryByStudnet(this.queryParams).then(response => {
        this.bclassList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    getClassTeacherList() {
      getClassTeacherList().then(response => {
        this.userOptions = response.data;
      });
    },
    // 字典设备状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 字典设备状态字典翻译
    classDeptFormat(row, column) {
      return this.selectDictLabel(this.classDeptOptions, row.classDept);
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        className: undefined,
        classTeacherId: undefined,
        status: "1",
        classDept: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        name: null,
        phone: null,
        id: this.id
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push("/educational/exam/editPaper");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection);
      this.rowList = selection;

      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push({
        path: "/educational/exam/examStudent",
        query: { id: row.id }
      });
    },
    submitPublish() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          publishTestPaper(this.form).then(resp => {
            this.msgSuccess("发布成功");
            this.publishAperVisible = false;
          });
        }
      });
    },
    handleClose() {
      this.publishAperVisible = false;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return deleteTestPaper(row.id);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },

    // 获取当前选中班主任的名称
    selectUser(val) {
      alert(val.label);
      this.form.username = val.label;
    }
  }
};
</script>

  <style lang='scss' scoped>
/deep/ .pigaiLabel {
  color: aquamarine;
}
</style>
  